package com.jlh.cookbook.utils;

import com.jlh.cookbook.core.RequestStatus;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.Map;

/**
 * com.jlh.cookbook.utils
 * Created by ASUS on 2017/3/4.
 * 14:53
 */
public class HttpClientUtils {
    private CloseableHttpClient httpClient;

    public HttpClientUtils() {
        httpClient = HttpClients.createDefault();
    }

    public String get(String url, Map<String, String> params) {
        CloseableHttpResponse response = null;
        try {
            HttpGet httpGet;
            StringBuilder target = new StringBuilder(url);
            if (params!=null&&!params.isEmpty()) {
                target.append("?");
                params.keySet().forEach(m -> {
                    target.append(m);
                    target.append("=");
                    target.append(params.get(m) + "&");
                });
                target.deleteCharAt(target.lastIndexOf("&"));
            }
            httpGet = new HttpGet(target.toString());
            httpGet.setHeader("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
            httpGet.setHeader("User-Agent","Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36");
            System.out.println(target.toString());
            response = httpClient.execute(httpGet);
            if(response.getStatusLine().getStatusCode()== RequestStatus._404)
                return RequestStatus.STR_404;
            try {
                HttpEntity httpEntity = response.getEntity();
                String res = EntityUtils.toString(httpEntity);
                System.out.println(res);
                return res;
            }finally {
                response.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
